/******************************************************
 *                                                     
 *              Score System               
 *                                                     
 *******************************************************/

/**
 * FileServlet.java
 *
 * 网页的响应Servlet
 *
 * @author sundy
 * @version 0.0.1
 * lastModified 2011-01-01
 */

package com.sundy.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sundy.core.Configuration;
import com.sundy.core.Utility;

public class FileServlet extends AbstractServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3634252953425505493L;

	public FileServlet() {
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String fileName = request.getParameter("name");
		if (fileName == null || fileName.equals("")) {
			Utility.showError(request, response, "参数错误");
			return;
		}
		String exportDir = Configuration.getProperty("/config/export-dir");
		String fileExport = exportDir + File.separator + fileName;
		File file = new File(fileExport);
		if (!file.exists()) {
			Utility.showError(request, response, "下载文件未找到！");
			return;
		}
		response.setHeader("Content-Type", "application/vnd.ms-excel");
		response.setHeader("Content-Disposition", "attachment;filename="
				+ fileName);
		OutputStream fileout = response.getOutputStream();
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			int size = fis.available();
			byte[] buffer = new byte[size];
			fis.read(buffer);
			fileout.write(buffer);
			fileout.flush();
		} finally {
			if (fis != null)
				fis.close();
		}
	}
}
